#include "stdafx.h"
#include "MRUCacheMappingFileReader.h"

namespace DataManager
{
namespace
{
	static int kAllocateGranularity = 0;
}


MRUCacheMappingFileReader::MRUCacheMappingFileReader( HANDLE file_handle ):file_handle_(file_handle)
{
	mapping_file_handle_.Set(::CreateFileMapping( file_handle ,NULL,PAGE_READONLY,0,0,NULL));
	DPCHECK(file_mapping_handle_);
	if( !kAllocateGranularity )
	{
		SYSTEM_INFO  sys_info;
		GetSystemInfo(&sys_info);
		kAllocateGranularity = static_cast<int>(sys_info.dwAllocationGranularity);
	}
 
	current_ptr_ =   NULL; 
	GetFileSize(file_handle, &file_size_);
	bytes_to_read_ = file_size_;
}

void MRUCacheMappingFileReader::SetCurrentRange( int pos, int bytes_count )
{
	MappingDataInfoList  iter =  mapping_block_list_.Get(pos) ;
	if( iter == mapping_block_list_.end() )
	{
		MappingDataInfo *  data_info = new MappingDataInfo;
		int  mapping_offset = pos /kAllocateGranularity*kAllocateGranularity;
		int  mapping_size = bytes_count + pos -  mapping_offset;

		void * mapping_pointer_ = MapViewOfFile(mapping_file_handle_,FILE_MAP_READ,0,mapping_offset, mapping_size );
		DPCHECK(mapping_pointer_);

		data_info->mapping_file_pointer.reset(mapping_pointer_);
		mapping_pointer_ = reinterpret_cast<char*>(mapping_pointer_) +( pos - mapping_offset );
	}
	
}

}